package com.qys.livesMall.common.message;


import com.qys.livesMall.common.enums.LanguageEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.*;

/**
 * 语言国际化工具类
 */
@Service
public class GlobalLanguageConvertor {

    // 默认绑定资源
    //<项目,<语言,文件>>
    public static volatile Map<String, Map<String,ResourceBundle>> bundles=new HashMap<>();


    /**
     * 初始化配置文件
     */
    private void initResources(String project) {
        try {

            // 提前加载好所有语言包，以便后台静态类全局提供服务
            Locale locale_cn = new Locale("zh", "CN");
            Locale locale_en = new Locale("en", "US");
            // 绑定语言包
            String lang_cn=locale_cn.getLanguage()+"_"+locale_cn.getCountry();
            String lang_en=locale_en.getLanguage()+"_"+locale_en.getCountry();
            ResourceBundle bundle_cn = ResourceBundle.getBundle("i18n/"+project+"_message_"+ lang_cn);
            ResourceBundle bundle_en = ResourceBundle.getBundle("i18n/"+project+"_message_"+ lang_en);

            HashMap<String,ResourceBundle> projectResourceBundle=new HashMap<>();
            projectResourceBundle.put(lang_cn,bundle_cn);
            projectResourceBundle.put(lang_en,bundle_en);
            bundles.put(project,projectResourceBundle);

        } catch (MissingResourceException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将提示语句翻译成用户登录所选语言的语句
     * @param key
     * @return
     */

    public String convertor(Locale locale, String key,String project ) {
        String language=locale.getLanguage()+"_"+locale.getCountry();
        Map<String,ResourceBundle> resourceBundleMap=bundles.get(project);
        if (resourceBundleMap==null){
            synchronized (ResourceBundle.class) {
                initResources(project);
            }
        }else {
            resourceBundleMap.get(language);
            if (null == resourceBundleMap.get(LanguageEnum.ZN_CN.getLang()) || null == resourceBundleMap.get(LanguageEnum.EN_US.getLang())) {
                synchronized (ResourceBundle.class) {
                    if (null == resourceBundleMap.get(LanguageEnum.EN_US.getLang())) {
                        initResources(project);
                    }
                }
            }
        }

        ResourceBundle bundle_cn = bundles.get(project).get(LanguageEnum.ZN_CN.getLang());
        ResourceBundle bundle_en = bundles.get(project).get(LanguageEnum.EN_US.getLang());

        String result;
        if (StringUtils.isEmpty(language)) {
            result = bundle_en.getString(key);
        } else if (LanguageEnum.ZN_CN.getLang().equals(language)) {
            result = bundle_cn.getString(key);
        } else if (LanguageEnum.EN_US.getLang().equals(language)) {
            result = bundle_en.getString(key);
        } else {
            result = bundle_en.getString(key);
        }
        return result;
    }


}

